<template>
  <view class="circle-detail-container">
    <!-- 圈子头部信息 -->
    <view class="circle-header">
      <image :src="circleInfo.cover_image" class="header-bg" mode="aspectFill"></image>
      <view class="header-overlay">
        <view class="circle-info">
          <view class="circle-avatar">
            <image :src="circleInfo.avatar || circleInfo.cover_image" class="avatar-image" mode="aspectFill"></image>
          </view>
          <view class="circle-details">
            <text class="circle-name">{{ circleInfo.cate_name }}</text>
            <text class="circle-desc">{{ circleInfo.description }}</text>
            <view class="circle-stats">
              <text class="stat-item">{{ circleInfo.member_count }}成员</text>
              <text class="stat-item">{{ circleInfo.post_count }}帖子</text>
            </view>
          </view>
          <view class="join-action">
            <u-button
              v-if="!circleInfo.isJoined"
              type="primary"
              size="small"
              :custom-style="{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', border: 'none' }"
              @click="handleJoinCircle"
            >
              {{ circleInfo.join_type === 1 ? '申请加入' : '立即加入' }}
            </u-button>
            <u-button
              v-else
              type="info"
              size="small"
              plain
              @click="handleLeaveCircle"
            >
              已加入
            </u-button>
          </view>
        </view>
      </view>
    </view>

    <!-- 导航标签 -->
    <view class="nav-tabs">
      <view
        class="tab-item"
        :class="{ active: currentTab === 'posts' }"
        @click="currentTab = 'posts'"
      >
        <text class="tab-text">动态</text>
      </view>
      <view
        class="tab-item"
        :class="{ active: currentTab === 'members' }"
        @click="currentTab = 'members'"
      >
        <text class="tab-text">成员</text>
      </view>
      <view
        class="tab-item"
        :class="{ active: currentTab === 'info' }"
        @click="currentTab = 'info'"
      >
        <text class="tab-text">介绍</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view
      class="content-area"
      scroll-y
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 动态列表 -->
      <view v-if="currentTab === 'posts'" class="posts-content">
        <view class="post-item modern-card" v-for="item in postList" :key="item.id">
          <!-- 帖子内容 -->
          <view class="post-header">
            <view class="user-info">
              <u-avatar :src="item.userAvatar" size="40"></u-avatar>
              <view class="user-details">
                <text class="username">{{ item.username }}</text>
                <text class="post-time">{{ formatTime(item.create_time) }}</text>
              </view>
            </view>
          </view>
          <view class="post-content">
            <text class="post-text">{{ item.content }}</text>
            <view class="post-images" v-if="item.images && item.images.length > 0">
              <image
                v-for="(img, index) in item.images"
                :key="index"
                :src="img"
                class="post-image"
                mode="aspectFill"
                @click="previewImage(item.images, index)"
              ></image>
            </view>
          </view>
          <view class="post-footer">
            <view class="interaction-buttons">
              <view class="interaction-btn" @click="handleLike(item)">
                <u-icon :name="item.isLiked ? 'heart-fill' : 'heart'" :color="item.isLiked ? '#ff4757' : '#999'" size="18"></u-icon>
                <text class="btn-text">{{ item.likeCount || 0 }}</text>
              </view>
              <view class="interaction-btn" @click="handleComment(item)">
                <u-icon name="chat" color="#999" size="18"></u-icon>
                <text class="btn-text">{{ item.commentCount || 0 }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 成员列表 -->
      <view v-if="currentTab === 'members'" class="members-content">
        <view class="member-item" v-for="item in memberList" :key="item.id">
          <u-avatar :src="item.avatar" size="50"></u-avatar>
          <view class="member-info">
            <text class="member-name">{{ item.username }}</text>
            <text class="member-role">{{ item.role === 'admin' ? '管理员' : '成员' }}</text>
          </view>
          <view class="member-actions">
            <u-button size="mini" type="primary" plain v-if="item.role !== 'admin'">关注</u-button>
          </view>
        </view>
      </view>

      <!-- 圈子介绍 -->
      <view v-if="currentTab === 'info'" class="info-content">
        <view class="info-section">
          <text class="section-title">圈子介绍</text>
          <text class="section-content">{{ circleInfo.description || '暂无介绍' }}</text>
        </view>
        <view class="info-section">
          <text class="section-title">创建时间</text>
          <text class="section-content">{{ formatTime(circleInfo.create_time) }}</text>
        </view>
        <view class="info-section">
          <text class="section-title">圈子规则</text>
          <text class="section-content">{{ circleInfo.rules || '暂无规则' }}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 发布按钮 -->
    <view class="fab-button" @click="handlePublish">
      <view class="fab-icon gradient-bg">
        <u-icon name="plus" color="white" size="28"></u-icon>
      </view>
    </view>

    
  </view>
</template>

<script>
import { requireLogin, isLoggedIn } from '@/utils/auth'
import categoryApi from '@/api/quanzi/category'
import postApi from '@/api/quanzi/post'


export default {
  data() {
    return {
      circleId: '',
      currentTab: 'posts',
      refreshing: false,
      loading: false,
      hasMore: true,
      page: 1,
      pageSize: 10,

      circleInfo: {},
      postList: [],
      memberList: []
    }
  },

  onLoad(options) {
    this.circleId = options.id
    this.loadCircleInfo()
    this.loadData()
  },

  methods: {
    async loadCircleInfo() {
      try {
        const res = await categoryApi.getInfo(this.circleId)
        if (res.code === 200 && res.data) {
          this.circleInfo = {
            id: res.data.cateId,
            cate_name: res.data.cateName,
            description: res.data.description || '暂无描述',
            cover_image: res.data.coverImage || 'https://cdn.uviewui.com/uview/album/1.jpg',
            member_count: res.data.memberCount || 0,
            post_count: res.data.postCount || 0,
            is_joined: res.data.isJoined || false,
            is_top: res.data.isTop || 0,
            create_time: res.data.createTime,
            tags: res.data.tags ? res.data.tags.split(',') : []
          }
        } else {
          this.showToast(res.msg || '加载圈子信息失败', 'error')
        }
      } catch (error) {
        console.error('加载圈子信息失败:', error)
        this.showToast('网络错误，请重试', 'error')
      }
    },

    async loadData() {
      if (this.currentTab === 'posts') {
        await this.loadPosts()
      } else if (this.currentTab === 'members') {
        await this.loadMembers()
      }
    },

    async loadPosts() {
      // 模拟帖子数据
      const mockPosts = [
        {
          id: 1,
          username: '摄影爱好者',
          userAvatar: 'https://cdn.uviewui.com/uview/album/2.jpg',
          content: '今天在校园里拍到的美景，分享给大家',
          images: ['https://cdn.uviewui.com/uview/album/3.jpg'],
          create_time: new Date().toISOString(),
          likeCount: 15,
          commentCount: 3,
          isLiked: false
        }
      ]
      this.postList = mockPosts
    },

    async loadMembers() {
      // 模拟成员数据
      const mockMembers = [
        {
          id: 1,
          username: '圈主',
          avatar: 'https://cdn.uviewui.com/uview/album/1.jpg',
          role: 'admin'
        },
        {
          id: 2,
          username: '摄影达人',
          avatar: 'https://cdn.uviewui.com/uview/album/2.jpg',
          role: 'member'
        }
      ]
      this.memberList = mockMembers
    },

    async onRefresh() {
      this.refreshing = true
      this.page = 1
      await this.loadData()
      this.refreshing = false
    },

    async loadMore() {
      if (this.loading || !this.hasMore) return
      this.page++
      await this.loadData()
    },

    formatTime(timeStr) {
      const time = new Date(timeStr)
      return time.toLocaleDateString()
    },

    async handleJoinCircle() {
      requireLogin(() => {
        this.circleInfo.isJoined = true
        this.circleInfo.member_count++
        this.showToast('加入成功', 'success')
      })
    },

    async handleLeaveCircle() {
      requireLogin(async () => {
        const res = await uni.showModal({
          title: '确认退出',
          content: '确定要退出这个圈子吗？'
        })

        if (res.confirm) {
          this.circleInfo.isJoined = false
          this.circleInfo.member_count--
          this.showToast('已退出圈子', 'success')
        }
      })
    },

    handlePublish() {
      requireLogin(() => {
        this.$tab.navigateTo(`/pages/publish/index?circleId=${this.circleId}`)
      })
    },

    handleLike(post) {
      requireLogin(() => {
        post.isLiked = !post.isLiked
        post.likeCount += post.isLiked ? 1 : -1
      })
    },

    handleComment(post) {
      requireLogin(() => {
        this.$tab.navigateTo(`/pages/post/detail?id=${post.id}`)
      })
    },

    previewImage(images, current) {
      uni.previewImage({
        urls: images,
        current: current
      })
    },

    showToast(title, type = 'default') {
      // 使用 uView 2.0 的 toast 方法
      this.$u.toast(title)
    }
  },

  watch: {
    currentTab() {
      this.page = 1
      this.loadData()
    }
  }
}
</script>

<style lang="scss" scoped>
.circle-detail-container {
  min-height: 100vh;
  background: #f8f9fa;
}

.circle-header {
  position: relative;
  height: 200px;

  .header-bg {
    width: 100%;
    height: 100%;
  }

  .header-overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
    padding: 20px 15px 15px;

    .circle-info {
      display: flex;
      align-items: flex-end;
      gap: 15px;

      .circle-avatar {
        .avatar-image {
          width: 60px;
          height: 60px;
          border-radius: 30px;
          border: 3px solid white;
        }
      }

      .circle-details {
        flex: 1;

        .circle-name {
          font-size: 20px;
          font-weight: bold;
          color: white;
          display: block;
          margin-bottom: 5px;
        }

        .circle-desc {
          font-size: 14px;
          color: rgba(255, 255, 255, 0.8);
          display: block;
          margin-bottom: 8px;
        }

        .circle-stats {
          display: flex;
          gap: 15px;

          .stat-item {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.8);
          }
        }
      }
    }
  }
}

.nav-tabs {
  display: flex;
  background: white;
  border-bottom: 1px solid #f0f0f0;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 15px 0;

    &.active {
      .tab-text {
        color: #667eea;
        font-weight: 600;
      }

      border-bottom: 2px solid #667eea;
    }

    .tab-text {
      font-size: 14px;
      color: #666;
    }
  }
}

.content-area {
  height: calc(100vh - 260px);
  padding: 15px;
}

.posts-content {
  .post-item {
    margin-bottom: 15px;
    padding: 15px;

    .post-header {
      margin-bottom: 10px;

      .user-info {
        display: flex;
        align-items: center;
        gap: 10px;

        .user-details {
          .username {
            font-size: 14px;
            font-weight: 600;
            color: #333;
            display: block;
          }

          .post-time {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }

    .post-content {
      .post-text {
        font-size: 14px;
        color: #666;
        line-height: 1.5;
        margin-bottom: 10px;
        display: block;
      }

      .post-images {
        display: flex;
        flex-wrap: wrap;
        gap: 5px;

        .post-image {
          width: calc(33.33% - 3.33px);
          height: 100px;
          border-radius: 8px;
        }
      }
    }

    .post-footer {
      margin-top: 15px;
      padding-top: 15px;
      border-top: 1px solid #f0f0f0;

      .interaction-buttons {
        display: flex;
        gap: 20px;

        .interaction-btn {
          display: flex;
          align-items: center;
          gap: 5px;

          .btn-text {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }
}

.members-content {
  .member-item {
    display: flex;
    align-items: center;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;

    .member-info {
      flex: 1;
      margin-left: 15px;

      .member-name {
        font-size: 14px;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 5px;
      }

      .member-role {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

.info-content {
  .info-section {
    margin-bottom: 20px;

    .section-title {
      font-size: 14px;
      font-weight: 600;
      color: #333;
      margin-bottom: 8px;
      display: block;
    }

    .section-content {
      font-size: 14px;
      color: #666;
      line-height: 1.5;
      display: block;
    }
  }
}

.fab-button {
  position: fixed;
  bottom: 100px;
  right: 20px;
  z-index: 998;

  .fab-icon {
    width: 56px;
    height: 56px;
    border-radius: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
  }
}
</style>
